import express, { Request, Response, Router } from 'express';
import { PrismaClient } from '@prisma/client';
import response from '../utils/response';
import { authenticateToken } from '../middleware/auth';
import upload from '../middleware/upload';

const router: Router = express.Router();
const prisma = new PrismaClient();

// 获取当前激活的顶部栏配置（客户端用）
router.get('/config/active', async (req: Request, res: Response) => {
  try {
    const config = await prisma.navbarConfig.findFirst({
      where: { isActive: true },
      include: {
        items: {
          where: { isVisible: true },
          orderBy: { sortOrder: 'asc' }
        }
      }
    });

    if (!config) {
      return response.error(res, '未找到激活的顶部栏配置', 404);
    }

    return response.success(res, config, '获取顶部栏配置成功');
  } catch (error) {
    console.error('获取顶部栏配置失败:', error);
    return response.error(res, '获取顶部栏配置失败');
  }
});

// 获取所有顶部栏配置（管理端用）
router.get('/config', authenticateToken, async (req: Request, res: Response) => {
  try {
    const configs = await prisma.navbarConfig.findMany({
      include: {
        items: {
          orderBy: { sortOrder: 'asc' }
        }
      },
      orderBy: { createdAt: 'desc' }
    });

    return response.success(res, configs, '获取所有顶部栏配置成功');
  } catch (error) {
    console.error('获取顶部栏配置失败:', error);
    return response.error(res, '获取顶部栏配置失败');
  }
});

// 创建新的顶部栏配置
router.post('/config', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { logo, items } = req.body;

    // 如果要设为激活，先将其他配置设为非激活
    await prisma.navbarConfig.updateMany({
      where: { isActive: true },
      data: { isActive: false }
    });

    const config = await prisma.navbarConfig.create({
      data: {
        logo,
        isActive: true,
        items: {
          create: items || []
        }
      },
      include: {
        items: true
      }
    });

    return response.success(res, config, '创建顶部栏配置成功');
  } catch (error) {
    console.error('创建顶部栏配置失败:', error);
    return response.error(res, '创建顶部栏配置失败');
  }
});

// 更新顶部栏配置
router.put('/config/:id', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { logo, isActive } = req.body;

    // 如果要设为激活，先将其他配置设为非激活
    if (isActive) {
      await prisma.navbarConfig.updateMany({
        where: { 
          isActive: true,
          NOT: { id: parseInt(id) }
        },
        data: { isActive: false }
      });
    }

    const config = await prisma.navbarConfig.update({
      where: { id: parseInt(id) },
      data: {
        logo,
        isActive
      },
      include: {
        items: true
      }
    });

    return response.success(res, config, '更新顶部栏配置成功');
  } catch (error) {
    console.error('更新顶部栏配置失败:', error);
    return response.error(res, '更新顶部栏配置失败');
  }
});

// 删除顶部栏配置
router.delete('/config/:id', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { id } = req.params;

    await prisma.navbarConfig.delete({
      where: { id: parseInt(id) }
    });

    return response.success(res, null, '删除顶部栏配置成功');
  } catch (error) {
    console.error('删除顶部栏配置失败:', error);
    return response.error(res, '删除顶部栏配置失败');
  }
});

// 创建顶部栏菜单项
router.post('/item', authenticateToken, async (req: Request, res: Response) => {
  try {
    const item = await prisma.navbarItem.create({
      data: req.body
    });

    return response.success(res, item, '创建菜单项成功');
  } catch (error) {
    console.error('创建菜单项失败:', error);
    return response.error(res, '创建菜单项失败');
  }
});

// 更新顶部栏菜单项
router.put('/item/:id', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { id } = req.params;

    const item = await prisma.navbarItem.update({
      where: { id: parseInt(id) },
      data: req.body
    });

    return response.success(res, item, '更新菜单项成功');
  } catch (error) {
    console.error('更新菜单项失败:', error);
    return response.error(res, '更新菜单项失败');
  }
});

// 删除顶部栏菜单项
router.delete('/item/:id', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { id } = req.params;

    await prisma.navbarItem.delete({
      where: { id: parseInt(id) }
    });

    return response.success(res, null, '删除菜单项成功');
  } catch (error) {
    console.error('删除菜单项失败:', error);
    return response.error(res, '删除菜单项失败');
  }
});

// 批量更新菜单项
router.put('/items/batch', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { configId, items } = req.body;

    // 先删除该配置下的所有菜单项
    await prisma.navbarItem.deleteMany({
      where: { configId: parseInt(configId) }
    });

    // 创建新的菜单项
    const newItems = await prisma.navbarItem.createMany({
      data: items.map((item: any) => ({
        ...item,
        configId: parseInt(configId)
      }))
    });

    // 获取更新后的配置
    const config = await prisma.navbarConfig.findUnique({
      where: { id: parseInt(configId) },
      include: {
        items: {
          orderBy: { sortOrder: 'asc' }
        }
      }
    });

    return response.success(res, config, '批量更新菜单项成功');
  } catch (error) {
    console.error('批量更新菜单项失败:', error);
    return response.error(res, '批量更新菜单项失败');
  }
});

// 上传Logo图片
router.post('/upload/logo', authenticateToken, upload.single('file'), async (req: any, res: Response) => {
  try {
    if (!req.file) {
      return response.error(res, '请选择要上传的文件');
    }

    // 构建HTTP访问URL
    const baseUrl = `${req.protocol}://${req.get('host')}`;
    const fileUrl = `${baseUrl}/uploads/${req.file.filename}`;

    // 记录文件上传信息
    const fileRecord = await prisma.fileUpload.create({
      data: {
        filename: req.file.filename,
        originalName: req.file.originalname,
        mimetype: req.file.mimetype,
        size: req.file.size,
        ossUrl: fileUrl,
        category: 'navbar',
        uploadedBy: req.user?.username
      }
    });

    return response.success(res, {
      url: fileUrl,
      fileId: fileRecord.id
    }, '上传Logo成功');
  } catch (error) {
    console.error('上传Logo失败:', error);
    return response.error(res, '上传Logo失败');
  }
});

export default router;